package com.zk.nakedfowl.dictionary.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.zk.nakedfowl.common.entity.Result;
import com.zk.nakedfowl.common.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;


import com.zk.nakedfowl.dictionary.dao.DictionaryDao;
import com.zk.nakedfowl.dictionary.pojo.Dictionary;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class DictionaryService {

	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private IdWorker idWorker;

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<Dictionary> findAll() {
		return dictionaryDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Dictionary> findSearch(Map whereMap, int page, int size) {
		Specification<Dictionary> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return dictionaryDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<Dictionary> findSearch(Map whereMap) {
		Specification<Dictionary> specification = createSpecification(whereMap);
		return dictionaryDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public Dictionary findById(String id) {
		return dictionaryDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param dictionary
	 */
	public void add(Dictionary dictionary) {
		dictionary.setId( idWorker.nextId()+"" );
		dictionaryDao.save(dictionary);
	}

	/**
	 * 修改
	 * @param dictionary
	 */
	public void update(Dictionary dictionary) {
		dictionaryDao.save(dictionary);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
		dictionaryDao.deleteById(id);
	}



	/**
	 * 通过parentId查询字典信息
	 * @param parentId
	 * @return Result
	 */
	public Result getDictionaryByPid(String parentId) {
		Sort sort=new Sort(Sort.Direction.ASC,"sort");

		Specification<Dictionary> specification=new Specification<Dictionary>() {
			@Override
			public Predicate toPredicate(Root<Dictionary> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
				// 父类编号
				if (parentId!=null && !"".equals(parentId)) {
					predicateList.add(cb.equal(root.get("parentId").as(String.class), parentId));
				}
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
			}
		};

		List<Dictionary> dictionaryList =  dictionaryDao.findAll(specification,sort);

		Result result = new Result();
		result.setData(dictionaryList);
		return result;
	}

	/**
	 * 查询字典信息列表
	 * @return Result
	 */
	public Result getDictionaryList() {
		Sort sort =  new Sort(Sort.Direction.ASC, "sort");
		List<Dictionary> dictionaryList=dictionaryDao.findAll(sort);

		return Result.success().add(dictionaryList);
	}

	/**
	 * 查询字典列表，并生成树形数据
	 * @return Result
	 */

	public Result getDictionaryTree() {
		//查询所有的分类信息
		List<Dictionary> dictionaryList =(List<Dictionary>) this.getDictionaryList().getData();

		//查询顶分类
		List<Dictionary> rootDictionaryList =(List<Dictionary>) this.getDictionaryByPid("0").getData();

		for (Dictionary dictionary : rootDictionaryList) {
			dictionary.setChildren(getChild(dictionary.getId(),dictionaryList));
		}
		Result result = new Result();
		result.setData(rootDictionaryList);
		return result;

	}

	private List<Dictionary> getChild(String id, List<Dictionary> dictionaryList) {
		// 子菜单
		List<Dictionary> childList = new ArrayList<>();

		// 遍历所有节点，将父菜单id与传过来的id比较
		for (Dictionary dictionary : dictionaryList) {
			if (dictionary.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
				if (dictionary.getParentId().equals(id)) {
					childList.add(dictionary);
				}
			}
		}

		// 把子菜单的子菜单再循环一遍
		for (Dictionary dictionary : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
			// 递归
			dictionary.setChildren(getChild(dictionary.getId(), dictionaryList));
		}
		// 递归退出条件
		if (childList.size() == 0) {
			return null;
		}
		return childList;
	}





	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<Dictionary> createSpecification(Map searchMap) {

		return new Specification<Dictionary>() {

			@Override
			public Predicate toPredicate(Root<Dictionary> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.equal(root.get("id").as(String.class), (String)searchMap.get("id")));
                }
				// 名称
				if (searchMap.get("name")!=null && !"".equals(searchMap.get("name"))) {
					predicateList.add(cb.equal(root.get("name").as(String.class), "%"+(String)searchMap.get("name")));
				}
                // 数据值（业务代码）
                if (searchMap.get("value")!=null && !"".equals(searchMap.get("value"))) {
                	predicateList.add(cb.equal(root.get("value").as(String.class), (String)searchMap.get("value")));
                }
                // 标签名
                if (searchMap.get("label")!=null && !"".equals(searchMap.get("label"))) {
                	predicateList.add(cb.like(root.get("label").as(String.class), "%"+(String)searchMap.get("label")+"%"));
                }
                // 类型
                if (searchMap.get("type")!=null && !"".equals(searchMap.get("type"))) {
                	predicateList.add(cb.like(root.get("type").as(String.class), "%"+(String)searchMap.get("type")+"%"));
                }
                // 中文类型名
                if (searchMap.get("zhType")!=null && !"".equals(searchMap.get("zhType"))) {
                	predicateList.add(cb.like(root.get("zhType").as(String.class), "%"+(String)searchMap.get("zhType")+"%"));
                }
                // 描述
                if (searchMap.get("description")!=null && !"".equals(searchMap.get("description"))) {
                	predicateList.add(cb.like(root.get("description").as(String.class), "%"+(String)searchMap.get("description")+"%"));
                }
                // 父级编号
                if (searchMap.get("parentId")!=null && !"".equals(searchMap.get("parentId"))) {
                	predicateList.add(cb.equal(root.get("parentId").as(String.class), (String)searchMap.get("parentId")));
                }
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

}
